package com.takwolf.libgdx.graphics;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class FontSheet {

    private static final String CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!'\";:()[]+-\\/*=%#  @"; // @代替版权符号

    private int charWidth;
    private int charHeight;
    private TextureRegion[] frames;

    public FontSheet(TextureRegion region) {
        charWidth = region.getRegionWidth() / 10;
        charHeight = region.getRegionHeight() / 6;
        TextureRegion[][] temp = region.split(charWidth, charHeight);
        frames = new TextureRegion[temp.length * temp[0].length];
        for (int i = 0; i < temp.length; i++) {
            System.arraycopy(temp[i], 0, frames, i * temp[i].length, temp[i].length);
        }
    }

    public FontSheet(Texture texture) {
        this(new TextureRegion(texture));
    }

    public int getCharWidth() {
        return charWidth;
    }

    public int getCharHeight() {
        return charHeight;
    }

    public TextureRegion getCharRegion(char c) {
        for (int i = 0; i < CHARSET.length(); i++) {
            if (CHARSET.charAt(i) == c) {
                return frames[i];
            }
        }
        return frames[frames.length - 1];
    }

    public void draw(Batch batch, String text, float x, float y) {
        text = text.toUpperCase();
        float startX = x;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            if (c == '\n') {
                x = startX;
                y -= getCharHeight();
            } else {
                batch.draw(getCharRegion(c), x, y - getCharHeight());
                x += getCharWidth();
            }
        }
    }

}
